package com.htfyun.ft.fragment.engineer;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.htfyun.ft.R;
import com.htfyun.ft.fragment.BaseFragment;
import com.htfyun.hardware.HTUpdateImageController;

import androidx.annotation.Nullable;


public class FragmentUpdateImage extends BaseFragment
            implements View.OnClickListener, HTUpdateImageController.OnHTUpdateImageListener {

    private final static String TAG = FragmentUpdateImage.class.getSimpleName();

    private TextView txtStatus;
    private Button btnStart;
    private Button btnCheck;
    private Button btnBroadcast;

    private HTUpdateImageController updateImageController = HTUpdateImageController.getInstance();

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_engineer_update_image;
    }

    @Override
    protected void onInitView(@Nullable Bundle savedInstanceState) {
        txtStatus = (TextView) findViewById(R.id.txtStatus);
        btnStart = (Button) findViewById(R.id.btnStart);
        btnCheck = (Button) findViewById(R.id.btnCheck);
        btnBroadcast = (Button) findViewById(R.id.btnBroadcast);
        txtStatus.setText("");

        btnStart.setOnClickListener(this);
        btnCheck.setOnClickListener(this);
        btnBroadcast.setOnClickListener(this);

    }

    private void updateStatus(String status) {
        String info = getString(R.string.update_image_status, status);
        txtStatus.setText(info);
    }

    @Override
    public void onClick(View v) {
        if (v == btnStart) {

            btnStart.setEnabled(false);

            updateStatus(getString(R.string.update_image_status_checking_img));

            updateImageController.startUpdateImage(this);

        } else if (v == btnCheck) {

            boolean ok = updateImageController.isUpdateImageSuccessful();

            String okString = getString(R.string.update_image_status_failed);
            if (ok) {
                okString = getString(R.string.update_image_status_success);
            }
            updateStatus(okString);

        } else if (v == btnBroadcast) {
            updateImageController.startUpdateImageByBroadcast(getContext());
        }
    }

    @Override
    public void onImageNotFound() {
        updateStatus(getString(R.string.update_image_status_img_not_found));
        btnStart.setEnabled(true);

    }

    @Override
    public void onImageVerify(boolean valid) {

        updateStatus(getString(valid ? R.string.update_image_status_img_is_valid : R.string.update_image_status_img_is_invalid));

        btnStart.setEnabled(true);

    }

    @Override
    public void onImageProductNameMismatch(String deviceProductName, String imageProductName) {

        updateStatus(getString(R.string.update_image_status_product_name_mismatch, deviceProductName, imageProductName));

        btnStart.setEnabled(true);
    }
}
